
<template>
  <el-dialog
    v-model="dialogVisible"
    title="添加菜品"
    width="80%"
    class="add-dish-dialog"
  >
    <div class="add-dish-content">
      <!-- 左侧 -->
      <div class="left-panel">
        <el-input
          v-model="searchKeyword"
          placeholder="请输入菜品名称进行搜索"
          clearable
          class="search-input"
          :prefix-icon="Search"
        />

        <!-- 分类浏览模式 -->
        <div class="dish-selector" v-show="!searchKeyword.trim()">
          <div class="category-tabs">
            <el-scrollbar>
              <span
                v-for="(item, index) in categoryList"
                :key="item.id"
                :class="{ active: activeCategoryIndex === index }"
                @click="handleCategoryClick(index, item.id)"
              >{{ item.name }}</span>
            </el-scrollbar>
          </div>
          <div class="dish-list-wrapper">
            <div class="dish-list-header">
              <span></span> <!-- 占位 -->
              <span>售卖状态</span>
              <span>价格</span>
              <span>菜品名称</span>
            </div>
            <el-scrollbar class="dish-list-scrollbar">
              <div v-for="item in currentDishList" :key="item.id" class="dish-item">
                <el-checkbox
                  :model-value="isChecked(item.id)"
                  @change="handleCheckboxChange(item, $event)"
                />
                <div class="item-content">
                  <span class="dish-name">{{ item.name }}</span>
                  <span class="dish-status">{{ item.status === 0 ? '停售' : '在售' }}</span>
                  <span class="dish-price">￥{{ item.price.toFixed(2) }}</span>
                </div>
              </div>
              <Empty v-if="!currentDishList.length && !loading" text="该分类下暂无菜品" />
            </el-scrollbar>
          </div>
        </div>

        <!-- 搜索结果模式 -->
        <div class="dish-selector" v-show="searchKeyword.trim()">
           <div class="dish-list-wrapper" style="padding-left: 0;">
             <div class="dish-list-header">
                <span></span> <!-- 占位 -->
                  <span>售卖状态</span>
              <span>价格</span>
              <span>菜品名称</span>
              </div>
              <el-scrollbar class="dish-list-scrollbar">
                <div v-for="item in searchedDishList" :key="item.id" class="dish-item">
                  <el-checkbox
                    :model-value="isChecked(item.id)"
                    @change="handleCheckboxChange(item, $event)"
                  />
                  <div class="item-content">
                    <span class="dish-name">{{ item.name }}</span>
                    <span class="dish-status">{{ item.status === 0 ? '停售' : '在售' }}</span>
                    <span class="dish-price">￥{{ item.price.toFixed(2) }}</span>
                  </div>
                </div>
                <Empty v-if="!searchedDishList.length && !loading" text="未搜索到菜品" />
              </el-scrollbar>
           </div>
        </div>
      </div>

      <!-- 右侧 -->
      <div class="right-panel">
        <div class="title">已选菜品 ({{ selectedDishes.length }})</div>
        <el-scrollbar class="selected-list">
          <div v-for="item in selectedDishes" :key="item.dishId" class="selected-item">
            <span class="dish-name">{{ item.name }}</span>
            <span class="dish-price">￥ {{ item.price.toFixed(2) }} </span>
            <span class="delete-icon" @click="removeSelectedDish(item)">
              <img src="@/assets/icons/btn_clean@2x.png" alt="删除">
            </span>
          </div>
        </el-scrollbar>
      </div>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleConfirm">添 加</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, watch, onMounted, computed } from 'vue';
import { getCategoryList } from '@/api/category';
import { getDishListByCategoryId, getDishPage } from '@/api/dish';
import type { ICategory } from '@/types/category';
import type { IDish, ISetMealDish } from '@/types/dish';
import Empty from '@/components/Empty/index.vue';
import { Search } from '@element-plus/icons-vue';

// --- Props & Emits ---
const props = defineProps<{
  visible: boolean,
  initialSelection: ISetMealDish[],
}>();
const emit = defineEmits(['update:visible', 'confirm']);

// --- Dialog Visibility ---
const dialogVisible = computed({
  get: () => props.visible,
  set: (val) => emit('update:visible', val)
});

// --- State ---
const loading = ref(false);
const searchKeyword = ref('');
const categoryList = ref<ICategory[]>([]);
const activeCategoryIndex = ref(0);
const currentDishList = ref<IDish[]>([]);
const searchedDishList = ref<IDish[]>([]);
const allDishesCache = new Map<number, IDish[]>();
const selectedDishes = ref<ISetMealDish[]>([]);

// --- API Calls ---
const fetchCategoriesAndInitialDishes = async () => {
  const catRes = await getCategoryList({ type: 1 });
  categoryList.value = catRes.data;
  if (categoryList.value.length > 0) {
    await fetchDishes(categoryList.value[0].id);
  }
};
const fetchDishes = async (categoryId: number) => {
  if (allDishesCache.has(categoryId)) {
    currentDishList.value = allDishesCache.get(categoryId)!;
  } else {
    loading.value = true;
    try {
      const dishRes = await getDishListByCategoryId({ categoryId });
      currentDishList.value = dishRes.data;
      allDishesCache.set(categoryId, dishRes.data);
    } finally {
      loading.value = false;
    }
  }
};
const searchDishesByName = async (name: string) => {
  loading.value = true;
  try {
    const dishRes = await getDishPage({ name, page: 1, pageSize: 1000 });
    searchedDishList.value = dishRes.data.records;
  } finally {
    loading.value = false;
  }
};

// --- Event Handlers ---
const handleCategoryClick = (index: number, categoryId: number) => {
  activeCategoryIndex.value = index;
  fetchDishes(categoryId);
};

// 核心修改 1：新的 checkbox change 处理逻辑
const handleCheckboxChange = (dish: IDish, isChecked: boolean) => {
  if (isChecked) {
    if (!selectedDishes.value.some(d => d.dishId === dish.id)) {
      selectedDishes.value.push({
        dishId: dish.id, name: dish.name, price: dish.price, copies: 1,
      });
    }
  } else {
    removeSelectedDish(dish);
  }
};

// 核心修改 2：用于判断 checkbox 是否应该被选中
const isChecked = (dishId: number) => {
  return selectedDishes.value.some(d => d.dishId === dishId);
};

const removeSelectedDish = (dishToRemove: { dishId: number }) => {
  selectedDishes.value = selectedDishes.value.filter(d => d.dishId !== dishToRemove.dishId);
};

const handleConfirm = () => {
  emit('confirm', selectedDishes.value);
};

// --- Watchers ---
watch(() => props.visible, (newVal) => {
  if (newVal) {
    // 核心修改 3：不再需要同步 checkedDishIds
    selectedDishes.value = JSON.parse(JSON.stringify(props.initialSelection));
  }
});
watch(searchKeyword, (newVal) => {
  const keyword = newVal.trim();
  if (keyword) {
    activeCategoryIndex.value = -1;
    searchDishesByName(keyword);
  } else if(categoryList.value.length > 0 && activeCategoryIndex.value === -1) {
    handleCategoryClick(0, categoryList.value[0].id);
  }
});

// --- Lifecycle Hook ---
onMounted(() => {
  fetchCategoriesAndInitialDishes();
});
</script>
<style lang="scss" scoped>
@import "@/styles/_variables.scss";

.add-dish-content {
  display: flex;
  height: 500px;
  border-top: 1px solid #e9e9e9;
  border-bottom: 1px solid #e9e9e9;
  margin: -20px 0;
}

.left-panel {
  width: 60%;
  border-right: 1px solid #e9e9e9;
  padding: 20px;
  display: flex;
  flex-direction: column;
}

.right-panel {
  width: 40%;
  padding: 20px;
  display: flex;
  flex-direction: column;
}

.search-input {
  margin-bottom: 20px;

  :deep(.el-input__wrapper) {
    border-radius: 20px;
  }
}

.dish-selector {
  display: flex;
  flex: 1;
  overflow: hidden;
}

.category-tabs {
  width: 120px;
  flex-shrink: 0;
  border-right: 1px solid #e9e9e9;

  span {
    display: block;
    text-align: center;
    padding: 15px 10px;
    cursor: pointer;
    position: relative;
    font-weight: 500;

    &.active {
      color: $sky-yellow;
      font-weight: bold;
    }
  }
}

.dish-list-wrapper {
  flex: 1;
  padding-left: 20px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.dish-list-scrollbar {
  flex: 1;
}

.title {
  font-weight: bold;
  margin-bottom: 20px;
  flex-shrink: 0;
}

.selected-list {
  flex: 1;
}

.selected-item {
  display: flex;
  align-items: center;
  padding: 10px 15px;
  margin-bottom: 15px;
  border-radius: 6px;
  background-color: #fff;
  border: 1px solid #f0f0f0;
  font-size: 14px;

  .dish-name {
    flex-grow: 1;
  }

  .dish-price {
    color: #666;
    margin: 0 15px;
  }

  .delete-icon {
    cursor: pointer;
    color: #999;
    flex-shrink: 0;

    img {
      width: 18px;
    }

    &:hover {
      color: $sky-yellow;
    }
  }
}

// --- 列表对齐样式 (定位方案) ---
.dish-list-header {
  position: relative;
  height: 40px;
  line-height: 40px;
  padding: 0 15px;
  font-size: 14px;
  color: #666;

  span:nth-child(2) {
    position: absolute;
    right: 100px;
    top: 0;
    text-align: center;
    width: 80px;
  }

  span:nth-child(3) {
    position: absolute;
    right: 20px;
    top: 0;
    text-align: center;
    width: 80px;
  }
}

.dish-item {
  position: relative;
  height: 40px;
  line-height: 40px;

  :deep(.el-checkbox) {
    width: 100%;
    height: 100%;
  }

  .item-content {
    margin-top: -40px;
    margin-left: 30px;
    .dish-name {
      display: inline-block;
      width: calc(100% - 200px);
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }

    .dish-status {
      position: absolute;
      right: 100px;
      top: 0;
      text-align: center;
      width: 80px;
      color: #666;
    }

    .dish-price {
      position: absolute;
      right: 20px;
      top: 0;
      text-align: center;
      width: 80px;
      color: #666;
    }
  }
}
</style>
